#!/usr/bin/env python3
"""
Example usage of the license plate removal OCR API endpoint
"""

import requests
from pathlib import Path

# API配置
API_BASE_URL = "http://localhost:8001"
API_ENDPOINT = "/api/ocr/digits_without_license_plate"

def upload_and_recognize_image_without_license_plate(image_path, confidence_threshold=0.8, remove_duplicates=True):
    """
    上传图片并进行OCR识别（自动去除车牌区域）
    
    Args:
        image_path: 图片文件路径
        confidence_threshold: 置信度阈值 (0.0-1.0)
        remove_duplicates: 是否去除重复数字
    
    Returns:
        dict: OCR识别结果
    """
    
    # 检查文件是否存在
    if not Path(image_path).exists():
        raise FileNotFoundError(f"图片文件不存在: {image_path}")
    
    # 准备请求参数
    params = {
        "confidence_threshold": confidence_threshold,
        "remove_duplicates": remove_duplicates
    }
    
    # 上传文件并处理
    try:
        with open(image_path, 'rb') as f:
            files = {'file': (Path(image_path).name, f, 'image/png')}
            
            print(f"正在上传并识别图片: {image_path}")
            print(f"参数: confidence_threshold={confidence_threshold}, remove_duplicates={remove_duplicates}")
            
            response = requests.post(
                f"{API_BASE_URL}{API_ENDPOINT}",
                files=files,
                params=params
            )
        
        # 处理响应
        if response.status_code == 200:
            result = response.json()
            return result
        else:
            raise Exception(f"API请求失败: {response.status_code} - {response.text}")
            
    except Exception as e:
        raise Exception(f"OCR处理失败: {str(e)}")

def print_ocr_results(result):
    """打印OCR识别结果"""
    
    if not result['success']:
        print(f"❌ 识别失败: {result['message']}")
        return
    
    data = result['data']
    
    print("\n" + "="*60)
    print("📋 车牌去除OCR识别结果")
    print("="*60)
    print(f"✅ 状态: {result['message']}")
    print(f"⏱️  处理时间: {data['processing_time']:.2f}秒")
    print(f"🌐 使用语言: {data['language_used']}")
    print(f"📊 平均置信度: {data['average_confidence']:.3f}")
    print(f"📝 总字符数: {data['total_characters']}")
    print(f"🔍 识别区域数: {len(data['results'])}")
    
    print(f"\n📄 完整文本:\n{data['total_text']}")
    
    if data['results']:
        print(f"\n📍 详细识别结果:")
        for i, item in enumerate(data['results'], 1):
            print(f"  {i}. 文本: '{item['text']}'")
            print(f"     置信度: {item['confidence']:.3f}")
            print(f"     坐标: {item['bbox']}")
            print()

def create_sample_images():
    """创建示例图片"""
    print("📷 创建示例图片...")
    
    # 创建包含车牌的图片
    from PIL import Image, ImageDraw, ImageFont
    
    # 图片1：包含车牌
    img1 = Image.new('RGB', (800, 600), color=(255, 255, 255))
    draw1 = ImageDraw.Draw(img1)
    
    try:
        font_large = ImageFont.truetype("arial.ttf", 48)
        font_medium = ImageFont.truetype("arial.ttf", 36)
    except:
        font_large = ImageFont.load_default()
        font_medium = ImageFont.load_default()
    
    # 添加常规数字文本
    draw1.text((50, 50), "Document ID: 12345", fill=(0, 0, 0), font=font_medium)
    draw1.text((50, 120), "Phone: +1 (555) 123-4567", fill=(0, 0, 0), font=font_medium)
    
    # 模拟车牌区域
    lp_x, lp_y = 200, 400
    lp_width, lp_height = 300, 80
    draw1.rectangle([lp_x, lp_y, lp_x + lp_width, lp_y + lp_height], outline=(0, 0, 0), width=2)
    draw1.text((lp_x + 20, lp_y + 20), "ABC-123-123", fill=(0, 0, 0), font=font_large)
    
    # 添加更多数字
    draw1.text((50, 300), "Serial: XYZ-789-789", fill=(0, 0, 0), font=font_medium)
    
    img1.save("license_plate_test_image.png")
    print(f"✅ 包含车牌的测试图片已创建: license_plate_test_image.png")
    
    # 图片2：不包含车牌
    img2 = Image.new('RGB', (800, 600), color=(255, 255, 255))
    draw2 = ImageDraw.Draw(img2)
    
    # 添加常规数字文本（无车牌）
    draw2.text((50, 50), "Document ID: 12345", fill=(0, 0, 0), font=font_medium)
    draw2.text((50, 120), "Phone: +1 (555) 123-4567", fill=(0, 0, 0), font=font_medium)
    draw2.text((50, 190), "Price: $99.99", fill=(0, 0, 0), font=font_medium)
    draw2.text((50, 300), "Serial: XYZ-789-789", fill=(0, 0, 0), font=font_medium)
    draw2.text((50, 400), "Account: 111-222-333", fill=(0, 0, 0), font=font_medium)
    
    img2.save("no_license_plate_test_image.png")
    print(f"✅ 不包含车牌的测试图片已创建: no_license_plate_test_image.png")

def main():
    """主函数示例"""
    
    print("🚗 车牌去除OCR API 使用示例")
    print("="*50)
    
    # 创建示例图片
    create_sample_images()
    
    # 示例1: 处理包含车牌的图片
    try:
        print("\n" + "="*60)
        print("处理包含车牌的图片")
        print("="*60)
        
        # 进行OCR识别（去除车牌）
        result = upload_and_recognize_image_without_license_plate(
            image_path="license_plate_test_image.png",
            confidence_threshold=0.8,  # 较高的置信度阈值
            remove_duplicates=True      # 去除重复数字
        )
        
        # 打印结果
        print_ocr_results(result)
        
        # 示例2: 处理不包含车牌的图片
        print("\n" + "="*60)
        print("处理不包含车牌的图片")
        print("="*60)
        
        result2 = upload_and_recognize_image_without_license_plate(
            image_path="no_license_plate_test_image.png",
            confidence_threshold=0.8,
            remove_duplicates=True
        )
        
        print_ocr_results(result2)
        
        # 示例3: 保留重复数字
        print("\n" + "="*60)
        print("处理包含车牌的图片（保留重复数字）")
        print("="*60)
        
        result3 = upload_and_recognize_image_without_license_plate(
            image_path="license_plate_test_image.png",
            confidence_threshold=0.8,
            remove_duplicates=False  # 保留重复数字
        )
        
        print_ocr_results(result3)
        
    except Exception as e:
        print(f"❌ 示例执行失败: {e}")
    
    print("\n" + "="*50)
    print("📚 API使用说明:")
    print("1. POST /api/ocr/digits_without_license_plate - 上传图片进行OCR识别（自动去除车牌）")
    print("2. 支持参数:")
    print("   - confidence_threshold: 置信度阈值 (0.0-1.0)")
    print("   - remove_duplicates: 是否去除重复数字 (true/false)")
    print("3. 支持格式: JPG, PNG, BMP, TIFF, WebP")
    print("4. 文件大小限制: 10MB")
    print("\n💡 提示:")
    print("  - 当检测到车牌时，系统会自动模糊处理车牌区域")
    print("  - 当未检测到车牌时，系统会直接对原图进行数字识别")
    print("  - 使用更高的置信度阈值可以过滤掉低质量的识别结果")
    print("  - 启用重复数字去除功能可以将'123123123'转换为'123'")

if __name__ == "__main__":
    main()